﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Primitives;
using JESAI.Application.Abstractions.Sys;
using JESAI.Application.Abstractions.Sys.Dtos;
using JESAI.Biz.Data.Enums;
using JESAI.Core.Aspects;
using JESAI.Core.Data.Pages;
using JESAI.Core.Http;
using JESAI.Core.Util.Extensions.Strings;
using JESAI.Framework.Filters;
using JESAI.Framework.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Threading.Tasks;
using JESAI.Biz.Data.Enums.Common;

namespace JESAI.Framework.Attributes
{
    [AttributeUsage(AttributeTargets.Method)]
    public class WebApiAuthorizationAttribute : ActionFilterAttribute
    {
        public override  void OnActionExecuting(ActionExecutingContext context)
        {
            IWebApiAuthorizationService _webApiAuthorizationService = ServiceLocator.Instance.GetServices<IWebApiAuthorizationService>().FirstOrDefault();
            ILogger<WebApiAuthorizationAttribute> _logger = ServiceLocator.Instance.GetServices<ILogger<WebApiAuthorizationAttribute>>().FirstOrDefault();
          
            var descriptor = context.ActionDescriptor as ControllerActionDescriptor;
            var actionName = descriptor?.ActionName;
            var controllerName = descriptor?.ControllerName;

            string? appKey = string.Empty;
            string? token = string.Empty;

            var headers  = context.HttpContext.Request.Headers; //await HttpRequestQueryParams.QueryParameters(context.HttpContext);
            if (headers.ContainsKey("Token"))
            {
                token = headers["Token"].ToString();
            }

            if (headers.ContainsKey("AppKey"))
            {
                appKey = headers["AppKey"].ToString();
            }
            string operationLog = String.Empty;
            if (string.IsNullOrWhiteSpace(appKey)|| string.IsNullOrWhiteSpace(token)||!_webApiAuthorizationService.WebApiAuthorize(appKey,token)) //APPKEY为空，则非法访问
            {
                ApiResult apiResult = new ApiResult(StatusCode.NotLogin, "没有授权的访问！");

                operationLog = JsonConvert.SerializeObject(apiResult) + "-token=" + token + "-AppKey=" + appKey;
                AddOperationLog(appKey, controllerName, actionName, operationLog);
                context.Result= apiResult;
                return;
            }
            operationLog = "登录成功!";
            AddOperationLog(appKey,controllerName,actionName,operationLog);
        }

        private void AddOperationLog(string appKey,string controllerName,string actionName,string operationLog)
        {
            IOperationLogService _operationLogService = ServiceLocator.Instance.GetServices<IOperationLogService>().FirstOrDefault();
            OperationLogDto operationLogDto = new OperationLogDto();
            operationLogDto.OperatorAppKey = appKey;
            operationLogDto.CreateTime = DateTime.Now;
            operationLogDto.ClassName = controllerName;
            operationLogDto.MethonName = actionName;
            operationLogDto.LogType = LogType.操作日志;
            operationLogDto.OperationLog = operationLog;
            operationLogDto.OperationName = "API登录";
            _operationLogService.AddOperationLogAsync(operationLogDto);
        }
    }
}
